package com.xx.happychatboot.middleware.netty.strategy.websocket;

import cn.hutool.json.JSONUtil;
import com.xx.happychatboot.middleware.netty.domain.enums.RocketMqTypeEnum;
import com.xx.happychatboot.middleware.netty.domain.enums.WebSocketTypeEnum;
import com.xx.happychatboot.middleware.netty.domain.vo.request.LoginWebSocketRequest;
import com.xx.happychatboot.middleware.netty.domain.vo.request.ReadAddFriendSocketRequest;
import com.xx.happychatboot.middleware.rocketmq.constants.RocketMqConstants;
import com.xx.happychatboot.middleware.rocketmq.domain.dto.RocketMqCommonDto;
import com.xx.happychatboot.middleware.rocketmq.utils.RocketMqProducer;
import com.xx.happychatboot.serve.user.mapper.UserApplyMapper;
import io.netty.channel.ChannelHandlerContext;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;

@Component
public class ReadAddFriendStrategy extends AbstractWebsocketStrategy{

    @Autowired
    private UserApplyMapper userApplyMapper;

    @Autowired
    private RocketMqProducer rocketMqProducer;

    @Override
    protected WebSocketTypeEnum getStrategyCode() {
        return WebSocketTypeEnum.READ_ADD_FRIEND;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void execute(ChannelHandlerContext channelHandlerContext, String data) {
        if (StringUtils.isBlank(data)) {
            return;
        }
        ReadAddFriendSocketRequest readAddFriendSocketRequest = JSONUtil.toBean(data, ReadAddFriendSocketRequest.class);
        if (Objects.isNull(readAddFriendSocketRequest) || CollectionUtils.isEmpty(readAddFriendSocketRequest.getIdList())) {
            return;
        }

        List<Long> idList = readAddFriendSocketRequest.getIdList();
        userApplyMapper.updateReadStatus(idList);

        RocketMqCommonDto rocketMqCommonDto = new RocketMqCommonDto();
        rocketMqCommonDto.setCode(RocketMqTypeEnum.READ_ADD_FRIEND.getCode());
        rocketMqCommonDto.setUid(readAddFriendSocketRequest.getUid());
        String key = RocketMqConstants.READ_ADD_FRIEND_KEY + readAddFriendSocketRequest.getUid();
        rocketMqProducer.sendSecureMsg(RocketMqConstants.READ_ADD_FRIEND_TOPIC,rocketMqCommonDto,key);
    }
}
